package edu.biwu.Request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig
public class ReqUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part uploadFile = request.getPart("uploadFile");

        String fileName = uploadFile.getSubmittedFileName();

        String extension = fileName.substring(fileName.lastIndexOf("."));//截取后缀名 .jpg
        String newFileName = UUID.randomUUID() + extension;

        //我们需要先选择服务端存储的位置
        File dir = new File("D:/uploadFile");
        if (!dir.exists()){
            dir.mkdirs();
        }

        //将上传文件写入指定路径
        uploadFile.write(dir+"/"+newFileName);//直接将上传路径写入指定位置

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileName+"上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
